package com.itmuch.cloud.study.util;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage.RecipientType;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;


public class EmailUtil {
    //主要利用message.setContent(content, "text/html;charset=utf-8");来实现发送html内容的邮件
    //private static final   String host = "smtp.sina.com"; //sina
    private static final String host = "smtp.mxhichina.com";//阿里云
    //private static final     String user = "xtdx888@sina.com";

    //private static final     String user = "sinotrans@jcmos.com";
    private static final String password = "sinotrans001";


    //发送单个邮件
    public static void send(String from, String to, String subject, String content) {
        Properties props = new Properties();
        props.put("mail.smtp.host", host); // 指定SMTP服务器
        props.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
        try {
            Session mailSession = Session.getDefaultInstance(props);
            Message message = new MimeMessage(mailSession);

            message.setFrom(new InternetAddress(from)); // 发件人

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人
            message.setSubject(subject); // 邮件主题
            //指定邮箱内容及ContentType和编码方式
            message.setContent(content, "text/html;charset=utf-8");
            //指定邮件发送日期
            message.setSentDate(new Date());
            message.saveChanges();
            Transport transport = mailSession.getTransport("smtp");
            transport.connect(host, from, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //批量发送邮件
    public static void send(String from, List<String> recipients, String subject, Object content, String filepath)
            throws AddressException, MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.host", host); // 指定SMTP服务器
        props.put("mail.smtp.auth", "true"); // 指定是否需要SMTP验证
        Session mailSession = Session.getDefaultInstance(props);
        Message message = new MimeMessage(mailSession);
        //   message.setFrom(new InternetAddress(from)); // 发件人
        message.setFrom(new InternetAddress("sinotrans@jcmos.com")); // 发件人
        //    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 收件人
        message.setSubject(subject); // 邮件主题
        //指定邮箱内容及ContentType和编码方式
        //  message.setContent(content, "text/html;charset=utf-8");
        //指定邮件发送日期
        message.setSentDate(new Date());
        //message.setFileName(arg0);

        // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
        Multipart multipart = new MimeMultipart();


        // 添加邮件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content.toString(), "text/html;charset=utf-8");
        multipart.addBodyPart(contentPart);
        // 设置邮件内容

        // 添加附件的内容
        if (filepath != null && !filepath.equals("")) {
            File file = new File(filepath);
            BodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(file);
            attachmentBodyPart.setDataHandler(new DataHandler(source));

            // 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
            // 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
           // BASE64Encoder enc = new BASE64Encoder();
           // messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");

            //MimeUtility.encodeWord可以避免文件名乱码
            try {
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            multipart.addBodyPart(attachmentBodyPart);
        }

        // 将multipart对象放到message中
        message.setContent(multipart);


        // 设置收件人们
        final int num = recipients.size();
        InternetAddress[] addresses = new InternetAddress[num];
        for (int i = 0; i < num; i++) {
            addresses[i] = new InternetAddress(recipients.get(i));
        }
        message.setRecipients(RecipientType.TO, addresses);
        // 设置主题

        message.saveChanges();
        // 发送
        Transport transport = mailSession.getTransport("smtp");

        transport.connect(host, from, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }





    // 拒收单导出
	/*	public static String rejectionExcelExport() throws Exception {
			List<Order> list=new ArrayList<Order>();
			for(int i=0;i<10;i++){
				Order order=new Order();
				order.setId(""+i);
				order.setName("name"+i);
				order.setCode("code"+i);
				list.add(order);
			}

		//	List<Order> list = orderService.rejectionExcelExport(order);// 获取数据
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String formatdate = format.format(new Date());
			String title = "金佰利单据" + formatdate;
			String creator = "";
            String path=System.getProperty("user.dir")+System.getProperty("file.separator")+title+""+".xls";
           // String path=title+""+".xls";
    		
            creator = "zhanglong";
			String[] hearders = null;
			String[] fields = null;
	
				hearders = new String[] { "托运单号", "订单类型", "商场订单号"  };// 表头数组

				fields = new String[] { "id", "code", "name" };// 拒收单对象属性数组

		

			TableData td = ExcelUtils.createTableData(list,
					ExcelUtils.createTableHeader(hearders), fields);
			JsGridReportBase report = new JsGridReportBase();
			report.exportToExcelForEmail(title, creator, td,path);
			list = null;
			return path;
		}*/


}
